﻿/* ApplicationMain.cs
 *
 * Shuriken is the legal property of its developers. Please refer to the
 * COPYRIGHT file distributed with this
 * source distribution.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */



using System;
using System.Collections.Generic;
using System.Text;
using Shuriken.Core;
using Shuriken.Core.Utils;

namespace Shuriken
{
    /// <summary>
    /// Main entry for the application 
    /// </summary>
    public class ApplicationMain
    {
        [STAThread]
        public static void Main(string[] args)
        {
            try
            {
                ApplicationEnvironment.Initialize(Properties.Settings.Default);
                ApplicationEnvironment.ProductNameShort = "Shuriken";
                ApplicationEnvironment.Parameters = new CommandLineParameters(args);

                CheckDelayedStartAndWait(); 

                // First thing to check for if we have another instanc e already running. 
                string single = ApplicationEnvironment.ProductNameShort + "_SingleInstance";
                LimitSingleInstance singleInstance = new LimitSingleInstance(single);

                if (singleInstance.IsAnotherInstanceRunning())
                {
                    return;
                }

                DateTime AppStart = DateTime.Now; 
                Tracer.WriteWarning("Application started. " + AppStart.ToString("yyyy/mm/dd hh:mm:ss"));

                ApplicationLauncher.Launch(args);

                DateTime AppEnd = DateTime.Now;
                Tracer.WriteWarning("Application done! " + AppEnd.ToString("yyyy/mm/dd hh:mm:ss"));
            }
            catch (Exception excp)
            {
               string msg = ApplicationEnvironment.Diagnostics.FormatCriticalError(excp);
                Tracer.WriteError(msg, "Unexpected Error");
            }
            finally
            {
                // final cleanup code comes here... 
            }
        }

        /// <summary>
        /// Checks if there is a delay and waits the time needed. 
        /// </summary>
        private static void CheckDelayedStartAndWait()
        {
            int delay = ApplicationEnvironment.Parameters.DelayedStart;
            System.Threading.Thread.Sleep(delay);
        }
    }
}
